<template>
  <div class="tags-add">
    <el-dialog
      :title="`${editData.id ? '修改目录' : '新增目录'}`"
      width="400px"
      :visible.sync="showDialog"
      @open="openDialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="所属学科" prop="subjectID">
          <el-select
            v-model="form.subjectID"
            style="width: 280px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in subject"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { simple, add, update } from '@/api/hmmm/tags.js'

export default {
  name: 'TagsAdd',
  props: {
    editData: {
      type: Object,
      default: () => {}
    }
  },

  data () {
    return {
      showDialog: false,
      form: {
        id: null,
        subjectID: null,
        tagName: null
      },
      subject: [],
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择所属学科',
            trigger: ['blur', 'change']
          }
        ],
        tagName: [
          {
            required: true,
            message: '请输入标签名称',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  methods: {
    openDialog () {
      this.getTagsSimpleList()
      this.showDialog = true
      if (this.editData.id) {
        this.form = { ...this.editData }
      } else {
        this.form = {
          id: null,
          subjectID: +this.$route.query.id || null,
          tagName: null
        }
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    async getTagsSimpleList () {
      const res = await simple()
      this.subject = res.data
    },

    handleSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        if (this.editData.id) {
          await update(this.form)
          this.$message.success('修改成功')
        } else {
          await add(this.form)
          this.$message.success('添加成功')
        }

        this.$emit('update')
        this.showDialog = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tags-add {
  .dialog-footer {
    text-align: right;
  }
}
</style>
